package com.siwei.apply.controller;

import com.siwei.apply.domain.res.JsgcghxkRes;
import com.siwei.apply.domain.res.JsgcghxkSinglRes;
import com.siwei.apply.domain.vo.JsgcghxkUpdateVo;
import com.siwei.apply.domain.vo.JsgcghxkVo;
import com.siwei.apply.domain.vo.OnChainVo;
import com.siwei.apply.service.JsgcghxkService;
import com.siwei.common.core.domain.R;
import com.siwei.common.core.web.controller.BaseController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 建设工程规划许可 控制器
 * 单独选址第六步
 * 批次报批第五步
 */
@RestController
@RequestMapping("/jsgcghxk")
public class JsgcghxkController extends BaseController {

    @Autowired
    private JsgcghxkService jsgcghxkService;

    /**
     * 添加建设工程规划许可
     */
    @PostMapping()
    public R<Map> Add(@RequestBody JsgcghxkVo jsgcghxkVo) {
        try {
            // Boolean b = jsgcghxkService.isExit(jsgcghxkVo.getProjectId());
            // if (b == true) {
            //     return R.fail("此项目已添加建设工程规划许可");
            // }
            // TODO 这里可以添加多个
            String id = jsgcghxkService.add(jsgcghxkVo);
            Map<String, String> map = new HashMap<>();
            map.put("id", id);
            return R.ok(map);
        } catch (Exception e) {
            return R.fail(e.getMessage());
        }
    }

    /**
     * 获取建设工程规划许可信息
     *
     * @param projectId 项目ID
     * @return 建设工程规划许可信息
     */
    @GetMapping("/{projectId}")
    public R<JsgcghxkRes> Get(@PathVariable String projectId) {
        try {
            return R.ok(jsgcghxkService.get(projectId));
        } catch (Exception e) {
            return R.fail(e.getMessage());
        }
    }

    /**
     * 通过主键id获取建设工程规划许可，返回结果与按projectId查询一致（单条结构）
     */
    @GetMapping("/id/{id}")
    public R<JsgcghxkSinglRes> GetById(@PathVariable String id) {
        try {
            return R.ok(jsgcghxkService.getById(id));
        } catch (Exception e) {
            return R.fail(e.getMessage());
        }
    }

    /**
     * 更新建设工程规划许可
     *
     * @param jsgcghxkUpdateVo 建设工程规划许可
     * @return 操作结果
     */
    @PutMapping()
    public R<Void> Update(@RequestBody JsgcghxkUpdateVo jsgcghxkUpdateVo) {
        try {
            jsgcghxkService.update(jsgcghxkUpdateVo);
            return R.ok();
        } catch (Exception e) {
            return R.fail(e.getMessage());
        }
    }

    /**
     * 更新建设工程规划许可的上链状态
     */
    @PutMapping("/onchain")
    public R<Void> updateHasOnchain(@RequestBody OnChainVo onChainVo) {
        try {
            for (String id : onChainVo.getIds()) {
                jsgcghxkService.updateHasOnchain(id, onChainVo.getHasOnchain());
            }
            return R.ok();
        } catch (Exception e) {
            return R.fail(e.getMessage());
        }
    }
}
